package com.abc.wy.exception;

import com.abc.wy.fdp.utils.ResponseMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class SCExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(SCException.class)
    public ResponseMsg handleFdpException(SCException ex){
        return ResponseMsg.error(ex.getErrorCode());
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public ResponseMsg handleDuplicateKeyException(DuplicateKeyException e){
        logger.error(e.getMessage(), e);
        return ResponseMsg.error(SCErrorCode.DUPLICATE_KEY_EXCEPTION);
    }

    @ExceptionHandler(AuthorizationException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResponseMsg handleAuthorizationException(AuthorizationException ex){
        logger.error(ex.getMessage(), ex);
        return ResponseMsg.error(ex.getErrorCode());
    }

    @ExceptionHandler(Exception.class)
    public ResponseMsg handleException(Exception ex){
        logger.error(ex.getMessage(), ex);
        // TODO 如果是测试环境，将e.getMessage()填充到errorMessage中
        return ResponseMsg.error(SCErrorCode.UNKNOWN_EXCEPTION);
    }
}
